<style lang="less" scoped>
@import "./user.less";
</style>
<template>
  <div>
    <Row>
      <Col span="24">
        <Card style="margin-bottom: 10px">
          <Form inline>
            <FormItem style="margin-bottom: 0" label="状态:">
              <Select
                v-model="searchConf.status"
                clearable
                placeholder="请选择状态"
                style="width: 100px"
              >
                <Option :value="1">启用</Option>
                <Option :value="0">禁用</Option>
              </Select>
            </FormItem>
            <FormItem style="margin-bottom: 0" label="类别:">
              <Select
                v-model="searchConf.type"
                clearable
                placeholder="请选择类别"
                style="width: 100px"
              >
                <Option :value="1">用户账号</Option>
                <Option :value="2">真实姓名</Option>
              </Select>
            </FormItem>
            <FormItem label="权限组:">
              <el-cascader
                placeholder="请选择权限组"
                :options="driverAll"
                expand-trigger="hover"
                @change="classChange2"
                :props="{ checkStrictly: true }"
                :value="[searchConf.groupId]"
                :show-all-levels="false"
                filterable
                size="small"
                clearable
              ></el-cascader>
            </FormItem>
            <FormItem style="margin-bottom: 0" label="查询条件:">
              <Input v-model="searchConf.keywords" placeholder></Input>
            </FormItem>
            <FormItem style="margin-top: 32px" label="">
              <Button type="primary" @click="search">查询/刷新</Button>
            </FormItem>
          </Form>
        </Card>
      </Col>
    </Row>
    <Row>
      <Col span="24">
        <Card>
          <p slot="title" style="height: 32px">
            <Button type="primary" @click="alertAdd" icon="md-add">新增</Button>
          </p>
          <div>
            <Table
              :columns="columnsList"
              :data="tableData"
              border
              disabled-hover
            >
              <template slot-scope="{ row }" slot="status">
                <el-switch
                  v-model="row.status == 1 ? true : false"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="switchClick(row)"
                ></el-switch>
              </template>
            </Table>
          </div>
          <div class="margin-top-15" style="text-align: center">
            <Page
              :total="tableShow.listCount"
              :current="tableShow.currentPage"
              :page-size="tableShow.pageSize"
              @on-change="changePage"
              @on-page-size-change="changeSize"
              show-elevator
              show-sizer
              show-total
            ></Page>
          </div>
        </Card>
      </Col>
    </Row>
    <Modal
      v-model="modalSetting.show"
      width="668"
      :styles="{ top: '30px' }"
      @on-visible-change="doCancel"
    >
      <p slot="header" style="color: #2d8cf0">
        <Icon type="md-information-circle"></Icon>
        <span>{{ formItem.id ? "编辑" : "新增" }}用户</span>
      </p>
      <Form
        ref="myForm"
        :rules="ruleValidate"
        :model="formItem"
        :label-width="80"
      >
        <FormItem label="用户账号" prop="username">
          <Input v-model="formItem.username" placeholder="请输入账号"></Input>
        </FormItem>
        <FormItem label="真实姓名" prop="nickname">
          <Input v-model="formItem.nickname" placeholder="请输入账号"></Input>
        </FormItem>
        <FormItem label="用户密码" prop="password">
          <Input
            v-model="formItem.password"
            type="password"
            placeholder="用户密码"
          ></Input>
        </FormItem>
        <FormItem label="手机号" prop="mobile">
          <Input v-model="formItem.mobile" placeholder="请输入手机号"></Input>
        </FormItem>
        <FormItem label="权限组" prop="groupId">
          <el-tree
            :data="groupList"
            show-checkbox
            node-key="id"
            ref="formTree"
            check-strictly
            highlight-current
            @check-change="handleClick"
            :default-expand-all="true"
            :props="defaultProps"
            :default-checked-keys="formItem.groupId"
          >
          </el-tree>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancel" style="margin-right: 8px"
          >取消</Button
        >
        <Button type="primary" @click="submit" :loading="modalSetting.loading"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import axios from "axios";
const editButton = (vm, h, currentRow, index) => {
  return h(
    "Button",
    {
      props: {
        type: "primary",
      },
      style: {
        margin: "0 5px",
      },
      on: {
        click: () => {
          vm.formItem.id = currentRow.id;
          vm.formItem.username = currentRow.username;
          vm.formItem.nickname = currentRow.nickname;
          vm.formItem.mobile = currentRow.mobile;
          vm.formItem.password = "ApiAdmin";
          axios.get("Auth/getGroups").then(function (response) {
            let res = response.data;
            if (res.code === 1) {
              vm.groupList = res.data.list;
            } else {
              if (res.code === -14) {
                vm.$store.commit("logout", vm);
                vm.$router.push({
                  name: "login",
                });
              } else {
                vm.$Message.error(res.msg);
              }
            }
          });
          vm.formItem.groupId = currentRow.groupId;
          vm.modalSetting.show = true;
          vm.modalSetting.index = index;
        },
      },
    },
    "编辑"
  );
};
const deleteButton = (vm, h, currentRow, index) => {
  return h(
    "Poptip",
    {
      props: {
        confirm: true,
        title: "您确定要删除这条数据吗? ",
        transfer: true,
      },
      on: {
        "on-ok": () => {
          axios
            .get("User/del", {
              params: {
                id: currentRow.id,
              },
            })
            .then(function (response) {
              currentRow.loading = false;
              if (response.data.code === 1) {
                vm.tableData.splice(index, 1);
                vm.$Message.success(response.data.msg);
              } else {
                vm.$Message.error(response.data.msg);
              }
            });
        },
      },
    },
    [
      h(
        "Button",
        {
          style: {
            margin: "0 5px",
          },
          props: {
            type: "error",
            placement: "top",
            loading: currentRow.isDeleting,
          },
        },
        "删除"
      ),
    ]
  );
};

export default {
  name: "system_user",
  data() {
    const rulesloginId = (rule, value, callback) => {
      if (
        !/^((\+|00)86)?((134\d{4})|((13[0-3|5-9]|14[1|5-9]|15[0-9]|16[2|5|6|7]|17[0-8]|18[0-9]|19[0-2|5-9])\d{8}))$/.test(
          value
        )
      ) {
        callback("手机号信息有误");
      } else {
        callback();
      }
    };
    return {
      driverAll: [],
      columnsList: [
        {
          title: "序号",
          type: "index",
          width: 65,
          align: "center",
        },
        {
          title: "用户账号",
          align: "center",
          key: "username",
          width: 120,
        },
        {
          title: "真实姓名",
          align: "center",
          key: "nickname",
          width: 120,
        },
        {
          title: "用户组",
          align: "center",
          key: "groupName",
          width: 120,
        },
        {
          title: "手机号",
          align: "center",
          key: "mobile",
          width: 200,
        },
        {
          title: "登录次数",
          align: "center",
          key: "loginTimes",
          width: 65,
        },
        {
          title: "最后登录时间",
          align: "center",
          key: "lastLoginTime",
          width: 160,
        },
        {
          title: "最后登录IP",
          align: "center",
          key: "lastLoginIp",
          width: 160,
        },
        {
          title: "状态",
          align: "center",
          slot: "status",
          width: 100,
        },
        {
          title: "操作",
          align: "center",
          key: "handle",
          width: 300,
          handle: ["edit", "delete"],
        },
      ],
      tableData: [],
      groupList: [],
      defaultProps: {
        children: "child",
        label: "name",
      },
      tableShow: {
        currentPage: 1,
        pageSize: 10,
        listCount: 0,
      },
      searchConf: {
        type: "",
        keywords: "",
        status: "",
        groupId: "",
      },
      modalSetting: {
        show: false,
        loading: false,
        index: 0,
      },
      formItem: {
        username: "",
        nickname: "",
        password: "",
        mobile: "",
        groupId: [],
        id: 0,
      },
      ruleValidate: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        nickname: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { validator: rulesloginId, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.init();
    this.getList();
    this.getDriver();
  },
  methods: {
    switchClick(row) {
      axios
        .get("/User/changeStatus", {
          params: {
            status: row.status == 1 ? 0 : 1,
            id: row.id,
          },
        })
        .then((response) => {
          if (response.data.code === 1) {
            this.$message({
              type: "success",
              message: response.data.msg,
              offset: 100,
            });
            this.getList();
          } else {
            this.$message({
              type: "error",
              message: response.data.msg,
              offset: 100,
            });
          }
        });
    },
    /**
     * tree 数据转换
     * @param  {Array} tree 待转换的 tree
     * @param  {Object} map  键值对映射
     * @return {Array}      转换后的 tree
     */
    convertTree(tree, map) {
      const result = [];
      // 遍历 tree
      tree.forEach((item) => {
        // 读取 map 的键值映射
        const value = item[map.value];
        const label = item[map.label];
        let children = item[map.children];
        // 如果有子节点，递归
        if (children) {
          children = this.convertTree(children, map);
        }
        result.push({
          value,
          label,
          children,
        });
      });
      return result;
    },
    getDriver() {
      let vm = this;
      axios.get("/Auth/getGroups").then(function (response) {
        let res = response.data;
        if (res.code === 1) {
          let obj = {
            value: "id",
            label: "name",
            children: "child",
          };
          vm.driverAll = vm.convertTree(res.data.list, obj);
        } else {
          if (res.code === -14) {
            vm.$store.commit("logout", vm);
            vm.$router.push({
              name: "login",
            });
          } else {
            vm.$message({
              message: res.msg,
              type: "warning",
            });
          }
        }
      });
    },
    classChange2(arr) {
      this.searchConf.groupId = arr[arr.length - 1];
    },
    handleClick(data, checked, node) {
      if (checked) {
        this.$refs.formTree.setCheckedNodes([data]);
      }
    },

    init() {
      let vm = this;
      this.columnsList.forEach((item) => {
        if (item.handle) {
          item.render = (h, param) => {
            let currentRowData = vm.tableData[param.index];
            return h("div", [
              editButton(vm, h, currentRowData, param.index),
              deleteButton(vm, h, currentRowData, param.index),
            ]);
          };
        }
        if (item.key === "status") {
          item.render = (h, param) => {
            let currentRowData = vm.tableData[param.index];
            return h(
              "i-switch",
              {
                attrs: {
                  size: "large",
                },
                props: {
                  "true-value": 1,
                  "false-value": 0,
                  value: currentRowData.status,
                },
                on: {
                  "on-change": function (status) {
                    axios
                      .get("User/changeStatus", {
                        params: {
                          status: status,
                          id: currentRowData.id,
                        },
                      })
                      .then(function (response) {
                        let res = response.data;
                        if (res.code === 1) {
                          vm.$Message.success(res.msg);
                        } else {
                          // param.row.status = currentRowData.status; // 给status赋当前值
                          // vm.changeStatus(params.row.id, str_status); // 改变状态的方法
                          vm.$message({
                            type: "error",
                            message: res.msg,
                            offset: 100,
                            duration: 4500,
                          });
                          vm.getList();
                        }
                        vm.cancel();
                      });
                  },
                },
              },
              [
                h(
                  "span",
                  {
                    slot: "open",
                  },
                  "启用"
                ),
                h(
                  "span",
                  {
                    slot: "close",
                  },
                  "禁用"
                ),
              ]
            );
          };
        }
      });
    },
    alertAdd() {
      let vm = this;
      axios.get("Auth/getGroups").then(function (response) {
        let res = response.data;
        if (res.code === 1) {
          vm.groupList = res.data.list;
        } else {
          if (res.code === -14) {
            vm.$store.commit("logout", vm);
            vm.$router.push({
              name: "login",
            });
          } else {
            vm.$Message.error(res.msg);
          }
        }
      });
      this.modalSetting.show = true;
    },
    submit() {
      let self = this;
      this.formItem.groupId = [];
      let ruleNodes = this.$refs["formTree"].getCheckedNodes();
      let ruleLength = ruleNodes.length;
      if (ruleLength) {
        for (let i = 0; i <= ruleLength - 1; i++) {
          this.formItem.groupId.push(ruleNodes[i]["id"]);
        }
      }
      if (this.formItem.groupId.length < 1) {
        this.$message({
          type: "error",
          message: "必须选择权限组",
          offset: 100,
        });
        return;
      }
      let obj = JSON.parse(JSON.stringify(this.formItem));
      obj.groupId = obj.groupId[0];
      this.$refs["myForm"].validate((valid) => {
        if (valid) {
          self.modalSetting.loading = true;
          let target = "";
          if (obj.id === 0) {
            target = "User/add";
          } else {
            target = "User/edit";
          }
          axios.post(target, obj).then(function (response) {
            if (response.data.code === 1) {
              self.$message({
                type: "success",
                message: response.data.msg,
                offset: 100,
                duration: 4500,
              });
              self.getList();
              self.cancel();
            } else {
              self.$message({
                type: "error",
                message: response.data.msg,
                offset: 100,
                duration: 4500,
              });
            }
            self.modalSetting.loading = false;
          });
        }
      });
    },
    cancel() {
      this.modalSetting.show = false;
    },
    doCancel(data) {
      if (!data) {
        this.formItem.id = 0;
        this.$refs["myForm"].resetFields();
        this.modalSetting.loading = false;
        this.modalSetting.index = 0;
      }
    },
    changePage(page) {
      this.tableShow.currentPage = page;
      this.getList();
    },
    changeSize(size) {
      this.tableShow.pageSize = size;
      this.getList();
    },
    search() {
      this.tableShow.currentPage = 1;
      this.getList();
    },
    getList() {
      let vm = this;
      let obj = {
        page: vm.tableShow.currentPage,
        size: vm.tableShow.pageSize,
        type: vm.searchConf.type,
        keywords: vm.searchConf.keywords,
        status: vm.searchConf.status,
        groupId: vm.searchConf.groupId,
      };
      for (let i in obj) {
        obj[i] ? obj[i] : delete obj[i];
      }
      axios
        .get("User/index", {
          params: obj,
        })
        .then(function (response) {
          let res = response.data;
          if (res.code === 1) {
            vm.tableData = res.data.list;
            vm.tableShow.listCount = res.data.count;
          } else {
            if (res.code === -14) {
              vm.$store.commit("logout", vm);
              vm.$router.push({
                name: "login",
              });
            } else {
              vm.$Message.error(res.msg);
            }
          }
        });
    },
  },
};
</script>
